import 'dart:io';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';

const List<String> _imagesList = [
  'http://ww3.sinaimg.cn/large/006y8mN6ly1g6e2tdgve1j30ku0bsn75.jpg',
  'http://ww3.sinaimg.cn/large/006y8mN6ly1g6e2whp87sj30ku0bstec.jpg',
  'http://ww3.sinaimg.cn/large/006y8mN6ly1g6e2tl1v3bj30ku0bs77z.jpg',
];

/// @description: 选择图片
/// @param {*}
/// @return {*} onChange
class CommonImagePicker extends StatefulWidget {
  const CommonImagePicker({Key? key, required this.onChange}) : super(key: key);

  final ValueChanged<List<XFile>> onChange;

  @override
  _CommonImagePickerState createState() => _CommonImagePickerState();
}

class _CommonImagePickerState extends State<CommonImagePicker> {
  // 图片文件列表
  List<XFile> files = [];
  final ImagePicker _picker = ImagePicker();
  _getImage() async {
    //选择相册
    final XFile? image =
        await _picker.pickImage(source: ImageSource.gallery, maxWidth: 400);
    if (null == image) return;
    setState(() {
      files = files..add(image);
    });
    //图片改变事件
    widget.onChange(files);
  }

  @override
  Widget build(BuildContext context) {
    // 图像宽高
    var width = (MediaQuery.of(context).size.width - 10.0 * 4) / 3;
    var height = 100.0;

    Widget addButton = GestureDetector(
      onTap: () {
        _getImage();
      },
      behavior: HitTestBehavior.translucent,
      child: Container(
        color: Colors.grey[200],
        margin: const EdgeInsets.only(left: 10),
        width: width,
        height: height,
        child: const Center(
          child: Icon(
            Icons.add,
            size: 26,
          ),
        ),
      ),
    );

    Widget imageWrapper(imgUrl) {
      // return
      return Stack(
        clipBehavior: Clip.none,
        children: [
          Padding(
            padding: const EdgeInsets.only(left: 10.0, bottom: 20.0),
            child: Image.file(
              File(imgUrl.path),
              width: width,
              height: height,
              fit: BoxFit.cover,
            ),
          ),
          Positioned(
              right: -20.0,
              top: -25.0,
              child: IconButton(
                  onPressed: () {
                    setState(() {
                      files = files..remove(imgUrl);
                    });
                    widget.onChange(files);
                  },
                  icon: const Icon(
                    Icons.delete_forever,
                    color: Colors.red,
                  )))
        ],
      );
    }

    List<Widget> list = files.map((i) => imageWrapper(i)).toList()
      ..add(addButton);
    return SizedBox(
      // width: 60,
      height: 200,
      child: Wrap(children: list),
    );
  }
}
